#include "client.h"
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

//全局变量userid
int userid = 0;

int loginFunc(int sockfd){
    char buf_name[128] = {0};
    char buf_pwd[64] = {0};
    char salt[13] = {0};
    char buf[512] = {0};
    Msg m;

    //while((getchar()) != '\n'); //清空输入缓冲区

    //对用户名的检查
    while(1){
        printf("username:");
        scanf("%s", buf_name);

        sendCmd(sockfd, CMD_TYPE_LOGIN1, buf_name);
        getMsg(sockfd, &m);

        if(m.type == MSG_TYPE_NOT_EXIST){
            printf("username does not exist.\n");
        } else if(m.type == MSG_TYPE_SUCCESS){
            strcpy(salt, m.data);   //拿到盐值
            break;
        } else{
            printf("unknown error.\n");
            exit(0);
        }
    }

    //对密码的检查
    for(int i = 0; i < 3; i++){

        char * temp = getpass("password:");
        strcpy(buf_pwd, temp);
        char * crypt_passwd = crypt(buf_pwd, salt);
        //格式化填充数据
        memset(buf, 0, sizeof(buf));
        sprintf(buf, "%s:%s", buf_name, crypt_passwd);

        sendCmd(sockfd, CMD_TYPE_LOGIN2, buf);

        getMsg(sockfd, &m);

        if(m.type == MSG_TYPE_SUCCESS){
            printf("login successfully.\n");
            userid = atoi(m.data);
            return 0;
        }else if(m.type == MSG_TYPE_WRONG_PASSWORD){
            printf("incorrect username or password.\n");
        }

    }
    printf("The maximum number of inputs has been reached\n");
    exit(0);
    return 0;
}

int loginFunc1(int sockfd){
    char buf[128] = {0};
    char buf_pwd[64] = {0};

    train_t t;
    fd_set rdset;

    for(int i = 0; i < 3; i++){
        printf("username:");
        scanf("%s", buf);
        char * temp = getpass("password:");
        strcpy(buf_pwd, temp);
        //用冒号分隔成 username:pwd这种
        strcat(buf,":");
        strcat(buf,buf_pwd);

        memset(&t, 0, sizeof(train_t));
        strncpy(t.buff, buf, sizeof(t.buff));
        t.len = strlen(t.buff);
        //这里原来是LOGIN
        t.type = CMD_TYPE_LOGIN1;

        sendn(sockfd, &t, 4 + 4 + t.len);

        FD_ZERO(&rdset);
        FD_SET(sockfd, &rdset);
        select(sockfd + 1, &rdset, NULL, NULL, NULL);

        int res = 0;
        if(FD_ISSET(sockfd, &rdset)){
            recv(sockfd, &res, sizeof(res), 0);
        }
        if(res == 1){
            printf("login successfully.\n");
            return 0;
        }else{
            printf("incorrect username or password.\n");
        }
    }
    printf("The maximum number of inputs has been reached\n");
    exit(0);

}
